<template>
  <div class="logistics-statistics">
    <!-- 概览卡片 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #ecf5ff">
              <el-icon :size="30" color="#409eff"><Van /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.totalOrders }}</div>
              <div class="stat-label">总订单数</div>
              <div class="stat-trend positive">
                <el-icon><CaretTop /></el-icon>
                <span>12.5%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #f0f9ff">
              <el-icon :size="30" color="#67c23a"><Checked /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.completedRate }}%</div>
              <div class="stat-label">完成率</div>
              <div class="stat-trend positive">
                <el-icon><CaretTop /></el-icon>
                <span>3.2%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #fef0f0">
              <el-icon :size="30" color="#f56c6c"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overview.totalRevenue }}</div>
              <div class="stat-label">总营收</div>
              <div class="stat-trend positive">
                <el-icon><CaretTop /></el-icon>
                <span>18.3%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #fdf6ec">
              <el-icon :size="30" color="#e6a23c"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.avgDeliveryTime }}h</div>
              <div class="stat-label">平均配送时长</div>
              <div class="stat-trend negative">
                <el-icon><CaretBottom /></el-icon>
                <span>5.1%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">订单趋势分析</span>
              <el-radio-group v-model="orderTrendType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="orderTrendChart" class="chart" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span class="title">订单状态分布</span>
          </template>
          <div ref="orderStatusChart" class="chart" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span class="title">承运商业务量对比</span>
          </template>
          <div ref="carrierChart" class="chart" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span class="title">配送区域分布</span>
          </template>
          <div ref="areaChart" class="chart" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <span class="title">配送效率Top10</span>
          </template>
          <el-table :data="efficiencyData" stripe>
            <el-table-column prop="rank" label="排名" width="80" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.rank <= 3" :type="getRankType(row.rank)" size="small">
                  {{ row.rank }}
                </el-tag>
                <span v-else>{{ row.rank }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="配送员" />
            <el-table-column prop="orders" label="订单数" align="right" />
            <el-table-column prop="completionRate" label="完成率" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.completionRate" :color="getProgressColor(row.completionRate)" />
              </template>
            </el-table-column>
            <el-table-column prop="avgTime" label="平均时长" align="center">
              <template #default="{ row }">
                {{ row.avgTime }}h
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <span class="title">异常订单统计</span>
          </template>
          <el-table :data="exceptionData" stripe>
            <el-table-column prop="type" label="异常类型" />
            <el-table-column prop="count" label="数量" align="right">
              <template #default="{ row }">
                <el-tag type="danger">{{ row.count }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" align="center" />
            <el-table-column prop="trend" label="趋势" align="center">
              <template #default="{ row }">
                <span :class="['trend', row.trend > 0 ? 'negative' : 'positive']">
                  <el-icon v-if="row.trend > 0"><CaretTop /></el-icon>
                  <el-icon v-else><CaretBottom /></el-icon>
                  {{ Math.abs(row.trend) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 综合统计 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">综合统计报表</span>
              <div>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  style="margin-right: 12px"
                />
                <el-button type="primary" size="small" @click="exportReport">
                  <el-icon><Download /></el-icon>
                  导出报表
                </el-button>
              </div>
            </div>
          </template>
          
          <el-descriptions :column="4" border>
            <el-descriptions-item label="总订单数">{{ summaryData.totalOrders }}</el-descriptions-item>
            <el-descriptions-item label="已完成">{{ summaryData.completed }}</el-descriptions-item>
            <el-descriptions-item label="运输中">{{ summaryData.shipping }}</el-descriptions-item>
            <el-descriptions-item label="异常订单">{{ summaryData.exception }}</el-descriptions-item>
            <el-descriptions-item label="总运费">¥{{ summaryData.totalFreight }}</el-descriptions-item>
            <el-descriptions-item label="总里程">{{ summaryData.totalDistance }} km</el-descriptions-item>
            <el-descriptions-item label="平均运费">¥{{ summaryData.avgFreight }}</el-descriptions-item>
            <el-descriptions-item label="平均时长">{{ summaryData.avgTime }}h</el-descriptions-item>
            <el-descriptions-item label="准时率">{{ summaryData.onTimeRate }}%</el-descriptions-item>
            <el-descriptions-item label="客户满意度">{{ summaryData.satisfaction }}%</el-descriptions-item>
            <el-descriptions-item label="投诉数">{{ summaryData.complaints }}</el-descriptions-item>
            <el-descriptions-item label="投诉率">{{ summaryData.complaintRate }}%</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Van, Checked, Money, Clock, CaretTop, CaretBottom, Download
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 概览数据
const overview = reactive({
  totalOrders: 1285,
  completedRate: 94.5,
  totalRevenue: '125,680',
  avgDeliveryTime: 4.2
})

// 图表类型
const orderTrendType = ref('day')
const dateRange = ref(null)

// 图表实例
let orderTrendChartInstance = null
let orderStatusChartInstance = null
let carrierChartInstance = null
let areaChartInstance = null

// 图表DOM引用
const orderTrendChart = ref(null)
const orderStatusChart = ref(null)
const carrierChart = ref(null)
const areaChart = ref(null)

// 效率数据
const efficiencyData = ref([
  { rank: 1, name: '张三', orders: 156, completionRate: 98, avgTime: 3.5 },
  { rank: 2, name: '李四', orders: 142, completionRate: 96, avgTime: 3.8 },
  { rank: 3, name: '王五', orders: 138, completionRate: 95, avgTime: 4.0 },
  { rank: 4, name: '赵六', orders: 125, completionRate: 94, avgTime: 4.2 },
  { rank: 5, name: '孙七', orders: 118, completionRate: 93, avgTime: 4.5 },
  { rank: 6, name: '周八', orders: 112, completionRate: 92, avgTime: 4.8 },
  { rank: 7, name: '吴九', orders: 108, completionRate: 91, avgTime: 5.0 },
  { rank: 8, name: '郑十', orders: 95, completionRate: 90, avgTime: 5.2 },
  { rank: 9, name: '钱十一', orders: 88, completionRate: 89, avgTime: 5.5 },
  { rank: 10, name: '陈十二', orders: 82, completionRate: 88, avgTime: 5.8 }
])

// 异常数据
const exceptionData = ref([
  { type: '配送延迟', count: 45, percentage: '3.5%', trend: -2.1 },
  { type: '货物损坏', count: 12, percentage: '0.9%', trend: 0.5 },
  { type: '地址错误', count: 28, percentage: '2.2%', trend: -1.3 },
  { type: '客户拒收', count: 8, percentage: '0.6%', trend: -0.8 },
  { type: '其他', count: 15, percentage: '1.2%', trend: 0.3 }
])

// 综合统计数据
const summaryData = reactive({
  totalOrders: 1285,
  completed: 1215,
  shipping: 45,
  exception: 25,
  totalFreight: '125,680',
  totalDistance: '45,280',
  avgFreight: '97.8',
  avgTime: 4.2,
  onTimeRate: 92.3,
  satisfaction: 96.5,
  complaints: 18,
  complaintRate: 1.4
})

// 获取排名类型
const getRankType = (rank) => {
  const typeMap = { 1: 'danger', 2: 'warning', 3: 'success' }
  return typeMap[rank] || ''
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 初始化订单趋势图
const initOrderTrendChart = () => {
  if (!orderTrendChart.value) return
  
  orderTrendChartInstance = echarts.init(orderTrendChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['订单数', '完成数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
        smooth: true,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '完成数',
        type: 'line',
        data: [110, 125, 95, 128, 85, 220, 200, 175, 185, 225, 280, 315],
        smooth: true,
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  orderTrendChartInstance.setOption(option)
}

// 初始化订单状态图
const initOrderStatusChart = () => {
  if (!orderStatusChart.value) return
  
  orderStatusChartInstance = echarts.init(orderStatusChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1215, name: '已完成' },
          { value: 45, name: '运输中' },
          { value: 15, name: '待发货' },
          { value: 10, name: '异常' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  orderStatusChartInstance.setOption(option)
}

// 初始化承运商图表
const initCarrierChart = () => {
  if (!carrierChart.value) return
  
  carrierChartInstance = echarts.init(carrierChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['顺丰速运', '圆通速递', '中通快递', '韵达快递', '申通快递']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '业务量',
        type: 'bar',
        data: [350, 280, 260, 220, 175],
        itemStyle: { color: '#409eff' }
      }
    ]
  }
  carrierChartInstance.setOption(option)
}

// 初始化区域图表
const initAreaChart = () => {
  if (!areaChart.value) return
  
  areaChartInstance = echarts.init(areaChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '配送区域',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 335, name: '北京' },
          { value: 310, name: '上海' },
          { value: 234, name: '广州' },
          { value: 135, name: '深圳' },
          { value: 271, name: '其他' }
        ]
      }
    ]
  }
  areaChartInstance.setOption(option)
}

// 导出报表
const exportReport = () => {
  ElMessage.success('报表导出成功')
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  orderTrendChartInstance?.resize()
  orderStatusChartInstance?.resize()
  carrierChartInstance?.resize()
  areaChartInstance?.resize()
}

onMounted(() => {
  setTimeout(() => {
    initOrderTrendChart()
    initOrderStatusChart()
    initCarrierChart()
    initAreaChart()
  }, 100)

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  orderTrendChartInstance?.dispose()
  orderStatusChartInstance?.dispose()
  carrierChartInstance?.dispose()
  areaChartInstance?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.logistics-statistics {
  .overview-row {
    margin-bottom: 20px;

    .stat-card {
      :deep(.el-card__body) {
        padding: 20px;
      }

      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
            margin-bottom: 8px;
          }

          .stat-trend {
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 4px;

            &.positive {
              color: #67c23a;
            }

            &.negative {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .trend {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;

    &.positive {
      color: #67c23a;
    }

    &.negative {
      color: #f56c6c;
    }
  }
}
</style>

